<template>
  <div class="ranking-wrapper">
    <h2 class="title">电影热度排行榜</h2>
    <div class="ranking-container">
      <div
          v-for="(movie, index) in movies"
          :key="movie.id"
          class="ranking-item"
      >
        <div class="rank" :class="{ 'top3': index < 3 }">{{ index + 1 }}</div>
        <div class="movie-info">
          <div class="name">{{ movie.title }}</div>
          <div class="heat">热度</div>
        </div>
        <el-button type="primary" size="small" @click="handlePurchase(movie)">购票</el-button>
      </div>
    </div>

    <!-- 购票对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="`购买《${selectedMovie?.title}》电影票`"
        width="600px"
        center
    >
      <div v-if="selectedMovie" class="movie-details">
        <div class="poster-container">
          <el-image :src="selectedMovie.poster" fit="cover" class="poster" />
        </div>
        <div class="info-container">
          <div class="info-row">
            <span class="label">影院：</span>
            <span class="value">{{ selectedMovie.cinema }}</span>
          </div>
          <div class="info-row">
            <span class="label">场次：</span>
            <span class="value">{{ selectedMovie.date }} {{ formatTime(selectedMovie.time) }}</span>
          </div>
          <div class="info-row">
            <span class="label">时长：</span>
            <span class="value">{{ selectedMovie.duration }}分钟</span>
          </div>
          <div class="info-row">
            <span class="label">类型：</span>
            <span class="value">{{ selectedMovie.genre }}</span>
          </div>
          <div class="info-row">
            <span class="label">原价：</span>
            <span class="value">¥{{ selectedMovie.price.toFixed(2) }}</span>
          </div>
          <div class="info-row">
            <span class="label">折扣：</span>
            <span class="value discount">-¥{{ selectedMovie.discount.toFixed(2) }}</span>
          </div>
          <div class="info-row">
            <span class="label">实付：</span>
            <span class="value final-price">¥{{ (selectedMovie.price - selectedMovie.discount).toFixed(2) }}</span>
          </div>
          <div class="info-row">
            <span class="label">剩余票数：</span>
            <span class="value" :class="{ 'low-stock': selectedMovie.amount <= 20 }">
              {{ selectedMovie.amount }} 张
            </span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPurchase" :loading="loading">
          {{ selectedMovie.amount > 0 ? '确认购买' : '已售罄' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import movieService from '@/services/movie';

const movies = ref([]);
const dialogVisible = ref(false);
const selectedMovie = ref(null);
const loading = ref(false);

const formatTime = (timeStr) => timeStr.split('.')[0];

const handlePurchase = (movie) => {
  selectedMovie.value = movie;
  dialogVisible.value = true;
};

const confirmPurchase = async () => {
  if (!selectedMovie.value || selectedMovie.value.amount <= 0) {
    ElMessage.warning('票已售罄，无法购买');
    return;
  }

  try {
    loading.value = true;
    await movieService.buyTicket(selectedMovie.value.id);

    // 更新库存
    selectedMovie.value.amount -= 1;
    ElMessage.success(`成功购买《${selectedMovie.value.title}》电影票`);
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error(`购票失败: ${error.response?.data?.message || '服务器错误'}`);
  } finally {
    loading.value = false;
  }
};

// 加载排行榜数据
movieService.getRanking()
    .then(res => movies.value = res.data || [])
    .catch(err => {
      ElMessage.error('数据加载失败');
      console.error('API错误', err);
    });
</script>

<style scoped>
.ranking-wrapper {
  padding: 24px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.title {
  font-size: 20px;
  margin-bottom: 16px;
  border-bottom: 2px solid #ff4d4f;
  padding-bottom: 8px;
}

/* 添加固定高度的滚动容器 */
.ranking-container {
  overflow-y: auto;
  height: 500px; /* 固定高度 */
  border: 1px solid #eaeaea;
  border-radius: 4px;
  padding: 0 10px;
}

.ranking-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #eaeaea;
}

.ranking-item:last-child {
  border-bottom: none; /* 最后一项不加下边框 */
}

.rank {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  margin-right: 16px;
  flex-shrink: 0; /* 防止被压缩 */
}

.top3 {
  background: #ff4d4f;
  color: white;
}

.movie-info {
  flex: 1;
  min-width: 0; /* 允许文本溢出时显示省略号 */
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.heat {
  color: #ff4d4f;
  font-size: 14px;
  display: flex;
  align-items: center;
}

/* 电影详情样式 */
.movie-details {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.poster-container {
  flex: 0 0 200px;
}

.poster {
  width: 200px;
  height: 300px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.info-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  font-size: 16px;
}

.label {
  width: 80px;
  color: #606266;
  font-weight: 500;
  text-align: right;
  margin-right: 12px;
}

.value {
  flex: 1;
  color: #303133;
}

.discount {
  color: #67C23A;
  font-weight: bold;
}

.final-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}
</style>